﻿using Framework.UI;
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using Framework.Scene;

namespace BridgeShips {

    public class LoadingUI : UIBase {

        private Slider m_slider;
        private Text  m_textNumber;
        private float m_progress = 0;
        private bool m_loadSceneComplete =false;
        public LoadSceneCallback m_callback = new LoadSceneCallback();

        public Image m_backGroundImage;
        private Vector4 m_screenResolution;
        void Start() {
            m_screenResolution = new Vector4( Screen.width, Screen.height, 0, 0 );
            if (m_backGroundImage != null) {
                m_backGroundImage.material.SetVector( "iResolution", m_screenResolution );
            }

            m_slider = transform.Find( "Slider" ).GetComponent<Slider>();
            m_textNumber = transform.Find( "Text" ).GetComponent<Text>();
            
            m_loadSceneComplete = false;
            if (GameEntry.Instance)
                GameEntry.Instance.SceneManager.LoadSceneAsync( "mainScene", m_callback );
        }

        public void Update() {

            if (m_backGroundImage != null) {
                m_backGroundImage.material.SetVector( "iResolution", m_screenResolution );
            }

            if (m_callback != null && GameEntry.Instance) {
               float progress = GameEntry.Instance.SceneManager.GetSceneOperationProgress() * 0.25f;
                if(progress >=0.1f && progress < 25.0f) {
                    m_progress = progress;
                }
                else {
                    m_progress += 0.5f;
                }
                SetLading( m_progress );

            }
        }

        private void SetLading(float progress) {
            if (progress < 100.0f) {
                progress = Mathf.Clamp(Mathf.Log10( progress * 0.1f),0,100);
                m_slider.value = progress;
                m_textNumber.text = "Loading... " + ( (int)(progress *100.0)).ToString() + "%";
                if(!m_loadSceneComplete )
                     m_loadSceneComplete = false;
            }
            else {
                if (!m_loadSceneComplete) {
                    m_loadSceneComplete = true;
                    m_progress = 100.0f;  m_slider.value = m_progress * 0.01f;
                    m_textNumber.text = "Loading... " + ((int)(m_progress)).ToString() + "%";

                    GameEntry.Instance.SceneManager.ActivationScene();

                    GameEntry.Instance.PostInit();
                }
          
            }
           
        }
    }
}
